import type { ColumnDialogEmits, ColumnDialogProps } from '../types/QueryCondition';
import { computed, reactive, ref } from 'vue';
import { t } from '@/locales';

export function useColumnDialog(props: ColumnDialogProps, emits: ColumnDialogEmits) {
  const firstOpenDialog = ref(true);
  const modelValue = computed(() => props.modelValue);

  const disabled = computed(() => props.dialogDisabled);

  const dialogMode = computed(() => props.dialogMode);

  const inheritList = computed(() => props.inheritList);

  const rules = reactive({
    roleCode: [
      { required: true, message: t('roleManage.placeholder.roleCode'), trigger: 'blur' },
    ],
    roleName: [
      { required: true, message: t('roleManage.placeholder.roleName'), trigger: 'blur' },
    ],
  });

  const formRefs = ref();

  // 使用计算属性简化双向绑定
  const dialogVisible = computed({
    get: () => props.visible,
    set: value => emits('update:visible', value),
  });

  // 关闭对话框
  const closeDialog = () => {
    dialogVisible.value = false;
  };

  async function submitDialog() {
    formRefs.value.validate().then((res: boolean) => {
      if (res) {
        // formRefs.value.get
        emits('change', modelValue.value);
        dialogVisible.value = false;
      }
    }).catch(() => {
      // 验证失败
    });
  }

  function openDialog() {
    if (firstOpenDialog.value && props.modelValue) {
      // formRefs.value.forEach((formRef) => {
      //   formRef?.form?.setValues(props.modelValue, 'overwrite')
      // })
      firstOpenDialog.value = false;
    }
  }
  const dialogWidth = computed(() => {
    return '850px';
  });

  return { dialogVisible, formRefs, dialogWidth, openDialog, submitDialog, closeDialog, modelValue, disabled, dialogMode, rules, inheritList };
}
